<template>
  <view class="home-content">
    <image src="https://s1.ax1x.com/2022/03/15/bvUvM4.gif" class="topimage"></image>
    <view class="addOrdersBtn" @tap="toPublish(queryParams.warrantyPersonId,phonenumber,nickname)">
      <image src="https://mkservice.mk-iot.com/subFile/mkApplet/report.png" class="addlogo"></image>
      我要报修
    </view>

    <view class="orderData">
      <view class="center">
        <view class="mySendOrder" @tap="toMyRepair(queryParams.warrantyPersonId)">
          <image src="https://mkservice.mk-iot.com/subFile/mkApplet/mysendorders.png"></image>
          <span>我的报修</span>
        </view>
        <view class="myOrderOver" @tap="toOverList(queryParams.warrantyPersonId)">
          <image src="https://mkservice.mk-iot.com/subFile/mkApplet/ordersover.png"></image>
          <span>已完成的</span>
        </view>
        <view class="adminShowOrder" @tap="toAdmin(queryParams.warrantyPersonId)">
          <image src="https://mkservice.mk-iot.com/subFile/mkApplet/adminshowordeer.png"></image>
          <span>待我处理</span>
        </view>
        <view class="maintenanceReport" @tap="maintenanceReport(queryParams.warrantyPersonId)">
          <image src="https://mkservice.mk-iot.com/subFile/mkApplet/count.png"></image>
          <span>维修统计</span>
        </view>
      </view>
    </view>

    <view class="orderslist">
      <view class="cu-bar bg-white">
        <view class="action">
          <text class="cuIcon-titles text-blue"></text>
          <text class="text-xl text-bold">我的未处理报修 ({{count}}条记录)</text>
        </view>
      </view>
      <view>
        <block v-for="(item,index) in maintenancelist" :key="index">
          <maintenance_list :mainteanceList="item"></maintenance_list>
        </block>
      </view>
    </view>
    <!-- 悬浮客服按钮 -->
    <view class="fenxiang" v-if="iscontactus==true">
      <button class="button-row" id="ContactusBtn" @tap="ContactusBtn" type="primary">
        <image src="https://mkservice.mk-iot.com/subFile/mkApplet/ContactusBtn.png"></image>
      </button>
    </view>
    <!-- 输入框示例 -->
    <uni-popup ref="popup" background-color="#fff" :show='show' @change="popupchange">
      <view class="popup-content">
        <uni-table ref="table" :loading="loading" border stripe emptyText="暂无更多数据"
          @selection-change="selectionChange">
          <uni-tr>
            <uni-th width="80" align="center">昵称</uni-th>
            <uni-th align="center">手机号</uni-th>
            <uni-th width="100" align="center">操作</uni-th>
          </uni-tr>
          <uni-tr v-for="(item, index) in userList" :key="index">
            <uni-td align="center">
              <view class="name">{{ item.nickName }}</view>
            </uni-td>
            <uni-td align="center">{{ item.phonenumber }}</uni-td>
            <uni-td align="center">
              <view class="uni-group">
                <button class="uni-button" size="mini" type="primary" @tap="clickUser(item.userId,item.nickName,item.phonenumber)">选择</button>
              </view>
            </uni-td>
          </uni-tr>
        </uni-table>
        <view class="uni-pagination-box"><uni-pagination show-icon :page-size="userqueryParams.pageSize"
            :current="userqueryParams.pageCurrent" :total="userTotal" @change="change" /></view>
      </view>
      <view class="btn_item">
        <button class="cancal" type="warn" @tap="close" size="mini">关闭</button>
      </view>
    </uni-popup>
    
    <!--底部-->
    <myBottom :mybottom="maintenancelist"></myBottom>
  </view>
</template>

<script>
  import {
    queryStateToList,
    addTaskState,
    sendMessage,
    updateTask,
  } from "@/api/system/task/task.js"
  import {
    getUserProfile,selectByRepairman,getUserItme
  } from "@/api/system/user"
   import myBottom from '../components/my-bottom/my-bottom.vue';
   import maintenance_list from '../components/maintenance-list/maintenance-list.vue';
  import {
    listMessage
  } from "@/api/system/message/message.js"
    import getDateTime from '../../utils/getdateTime.js'
  import config from "../../config"
  export default {
    components: {
      myBottom,
      maintenance_list
    },
    data() {
      return {
        tmplIds: [],
        ids: null,
        //客服开关显示
        iscontactus: false,
        // 是否正在请求数据,节流阀
        isloading: false,
        refreshIfNeeded: false,
        // 查询参数
        count: 0,
        is_open: false,
        queryParams: {
          pageNum: 1,
          pageSize: 5,
          warrantyPersonId: null,
          maintenanceStatus: 0,
        },
        queryMessageParams: {
          pageNum: 1,
          pageSize: 10,
          title: null,
          templateId: null
        },
        maintenancelist: [],
        phonenumber: null,
        nickname: null,
        maintenanceCode: null,
        maintainerId: null,
        warrantyPersonId: null,
        distributionType:null,
        urgency:null,
        loading: false,
        maintenanceMyList: [],
        userList: [],
        userqueryParams: {
          pageNum: 1,
          pageSize: 5
        },
        stateData: {
          maintenanceCode: null,
          state: "",
          datetime: getDateTime.dateTimeStr('y-m-d h:i:s'),
          descs: ""
        },
        // 用户数据总量
        userTotal: 0,
        flag: false ,//防止多次点击
      }
    },
    onLoad() {
      uni.setKeepScreenOn({
      	keepScreenOn: true
      });
      this.maintenancelist = []
      //重新进入首页查询userid
      getUserProfile().then(response => {
        this.queryParams.warrantyPersonId = response.data.userId
        this.phonenumber = response.data.phonenumber
        this.nickname = response.data.nickName
        this.queryMyToList()
      })
    },
    //页面创建时调用数据刷新
    created() {
      uni.$on("toIndex", (data) => {
        this.maintenancelist = []
        this.queryParams.pageNum = data.value
        this.queryMyToList()
      });
    },
    //防止页面重复调用
    onUnload() {
      // 移除监听事件
      uni.$off("toIndex");
    },
    //点击导航栏刷新首页数据
    onTabItemTap(e) {
      this.maintenancelist = []
      this.queryParams.pageNum = 1
      if (this.queryParams.warrantyPersonId != null) {
        this.queryMyToList()
      }
    },
    methods: {
      queryMyToList(cb) {
        // 打开遮罩层
        this.$modal.loading("数据加载中...");
        // ** 打开节流阀
        this.isloading = true
        queryStateToList(this.queryParams).then(response => {
          if (response.code === 200) {
            // 关闭遮罩层
            this.$modal.closeLoading();
            uni.stopPullDownRefresh()
            // 关闭节流阀
            this.isloading = false
            // 只要数据请求完毕，就立即按需调用 cb 回调函数
            cb && cb()
            this.maintenancelist = [...this.maintenancelist, ...response.rows]
            this.count = response.total
          }
        })
      },
      //点击我要报修
      toPublish(userid, phonenumber, nickname) {
        if (!this.flag) {
          if (this.$auth.hasRole("common")) {
            this.flag = true
            this.$modal.loading("数据加载中...");
            const url = '/subpkg/maintenance/maintenance_edit?userid=' +
              userid + '&phonenumber=' + phonenumber + "&nickname=" + nickname;
            this.sendSubscriptions(url)
          } else {
            uni.showModal({
              cancelColor: 'cancelColor',
              title: "提示",
              content: "您不是报修人员，无法进入本功能",
              showCancel: false
            })
          }
        }
      },
      //发送消息方法
      sendSubscriptions(url) {
        uni.getSetting({
          withSubscriptions: true,
          success: (res) => {
            //判断是否点击订阅
            if (res.subscriptionsSetting.mainSwitch) {
              //查询用户订阅的消息有哪些
              listMessage(this.queryMessageParams).then(response => {
                if (response.code == 200 && response.rows[0] != null) {
                  this.ids = response.rows.map(item => item.id)
                  this.tmplIds = response.rows.map(item => item.templateId)
                  // 关闭遮罩层
                  this.$modal.closeLoading();
                  uni.requestSubscribeMessage({
                    tmplIds: this.tmplIds,
                    success: (res) => {
                      this.flag = false
                      this.$tab.navigateTo(url)
                    },
                    fail(err) {
                      this.flag = false
                    }
                  })
                } else {
                  this.flag = false
                  this.$tab.navigateTo(url)
                }
              })
            } else {
              this.flag = false
              uni.showModal({
                title: '提示',
                content: '您已关闭消息订阅，请开启后再进行操作',
                showCancel: false,
              });
            }
          }
        })
      },
      //点击我的报修
      toMyRepair(userid) {
        if (!this.flag) {
          if (this.$auth.hasRole("common")) {
            this.flag = true
            this.$modal.loading("数据加载中...");
            const url = '/subpkg/maintenance/my-maintenance?userid=' + userid;
            this.sendSubscriptions(url)
          } else {
            uni.showModal({
              cancelColor: 'cancelColor',
              title: "提示",
              content: "您不是报修人员，无法进入本功能",
              showCancel: false
            })
          }
        }
      },
      //点击我的已完成的
      toOverList(userid) {
        if (!this.flag) {
          if (this.$auth.hasRole("common")) {
            this.flag = true
            this.$modal.loading("数据加载中...");
            const url = '/subpkg/maintenance/maintenance_overlist?userid=' + userid;
            this.sendSubscriptions(url)
          } else {
            uni.showModal({
              cancelColor: 'cancelColor',
              title: "提示",
              content: "您不是报修人员，无法进入本功能",
              showCancel: false
            })
          }
        }
      },
      //待我处理的
      toAdmin(userid) {
        if (!this.flag) {
          if (this.$auth.hasRoleOr(["admin", "repairman"])) {

            this.flag = true
            this.$modal.loading("数据加载中...");
            const url = '../maintenance/declaration_management?userid=' + userid;
            this.sendSubscriptions(url)
          } else {
            uni.showModal({
              cancelColor: 'cancelColor',
              title: "提示",
              content: "您不是工作人员，无法进入本功能",
              showCancel: false
            })
          }
        }
      },
      maintenanceReport(userId){
        //维修报表，管理员查询所有的，报修人员查看自己的
         this.$tab.navigateTo('../reportforms/report_forms?userId=' +userId)
      },
      //点击客服
      ContactusBtn() {},
      //弹窗时出现滑动穿透解决方案
          popupchange(e) {
            this.show = e.show
          },
      /**查询用户列表 */
          getuserList() {
            this.loading = true;
            selectByRepairman(this.userqueryParams).then(response => {
              this.userList = response.rows;
              this.loading = false;
            });
          },
          // 分页触发
          change(e) {
            this.userqueryParams.pageNum = e.current
            this.getuserList()
          },
          //选择派发人员取消
          close() {
            // TODO 做一些其他的事情，before-close 为true的情况下，手动执行 close 才会关闭对话框
            this.$refs.popup.close()
          },
          clickUser(userid,nickName,phonenumber) {
            if (this.maintenanceCode !== null && userid !== null) {
              this.$modal.confirm('确定派发该用户去维修吗？').then(() => {
                this.stateData.maintenanceCode = this.maintenanceCode
                this.stateData.state = this.distributionType==1?"维修中":'已重新派单，维修中'
                addTaskState(this.stateData).then(response => {
                  if (response.code == 200) {
                    const data = {
                      maintenanceCode: this.maintenanceCode,
                      maintenanceStatus: 1,
                      warrantyPersonId:this.warrantyPersonId,
                      maintainerId: userid,
                      startTime: getDateTime.dateTimeStr('y-m-d h:i:s')
                    }
                    updateTask(data).then(response => {
                      if (response.code === 200) {
                        getUserItme(userid).then(response => {
                          if (response.code == 200 && response.data.openId !=
                            null) {
                            //新增成功调用接口
                            const messagedata = {
                              openid: response.data.openId,
                              selfPage: '/pages/login',
                              maintenanceCode: this.maintenanceCode,
                              urgency: this.urgency == 0 ? '普通维修' : '紧急维修',
                              username: nickName,
                              phonenumber: phonenumber,
                              description: this.urgency == 0 ? '您有一份普通维修单,请在7天内及时处理' : '您有一份紧急维修单,请在3天内及时处理'
                            }
                            sendMessage(messagedata).then(response => {
                              //重置关键数据
                              //操作成功跳转到当前处理中
                             this.empty()
                             this.queryMyToList()
                              if (response.errcode == 0) {
                                this.$modal.msgSuccess("派发成功！")
                                this.$refs.popup.close()
                              } else {
                                 this.$modal.msgError("订阅失败");
                                 this.$refs.popup.close()
                              }
                            })
                          } else {
                            this.empty()
                            this.queryMyToList()
                            this.$modal.msgSuccess("派发成功！")
                            this.$refs.popup.close()
                          }
                        })
                      }
                    })
                  }
                })
              })
            }
          },
      //清控数据
      empty() {
        //重置关键数据
        this.count = 0
        this.isloading = false
        this.maintenancelist = []
        this.queryParams.pageNum = 1
      },
    },
    // 触底的事件
    onReachBottom() {
      // 判断是否还有下一页数据
      if (this.queryParams.pageNum * this.queryParams.pageSize >= this.count) return uni.$showMsg('数据加载完毕')
      // 判断是否正在请求其它数据，如果是，则不发起额外的请求
      if (this.isloading) return
      //让页码值自增+1
      this.queryParams.pageNum += 1
      // 重新获取列表数据
      this.queryMyToList()
    },
    //下拉事件
    onPullDownRefresh() {
      this.empty()
      //重新发起数据请求
      this.queryMyToList()
    },
  }
</script>

<style lang="scss">
  .home-content {
    .topimage {
      width: 100%;
      height: 150px;
    }

    .addOrdersBtn {
      width: 60%;
      height: 45px;
      border-radius: 20px;
      background-color: #fff;
      margin: -30px auto;
      box-shadow: 0px 5px 10px rgb(194, 194, 194);
      position: relative;
      text-align: center;
      line-height: 45px;
      z-index: 99;
      font-size: 16px;
      font-weight: bold;

      .addlogo {
        width: 40rpx;
        height: 40rpx;
        vertical-align: middle;
        margin-right: 5px;
      }
    }

    .addOrdersBtn:active {
      width: 60%;
      height: 45px;
      border-radius: 20px;
      background-color: rgb(238, 238, 238);
      margin: -30px auto;
      box-shadow: 0px 5px 10px rgb(194, 194, 194);
      position: relative;
      text-align: center;
      line-height: 45px;
      z-index: 99;
      font-size: 16px;
      font-weight: bold;
    }

    .orderData {
      background-color: #fff;
      width: 100%;
      height: 270rpx;
      border-radius: 10px;
      margin: 0px auto;
      padding-top: 45px;
      overflow: hidden;

      .center {
        margin: 0px auto;
        overflow: hidden;

        .mySendOrder {
          width: 22%;
          height: 70px;
          float: left;
          text-align: center;
          background-color: #37ADFF;
          border-radius: 10px;
          margin: 5px;
          margin-left: 10px;
          line-height: 70px;
          color: #fff;
          font-weight: bold;
        }

        .mySendOrder:active {
          width: 22%;
          height: 70px;
          float: left;
          text-align: center;
          background-color: #3095dd;
          border-radius: 10px;
          margin: 5px;
          margin-left: 10px;
          line-height: 70px;
          color: #fff;
          font-weight: bold;
        }

        .mySendOrder image {
          width: 20px;
          height: 20px;
          vertical-align: middle;
        }

        .myOrderOver {
          width: 22%;
          height: 70px;
          float: left;
          text-align: center;
          background-color: #FDC860;
          border-radius: 10px;
          margin: 5px;
          line-height: 70px;
          color: #fff;
          font-weight: bold;
        }

        .myOrderOver:active {
          width: 22%;
          height: 70px;
          float: left;
          text-align: center;
          background-color: #dbae53;
          border-radius: 10px;
          margin: 5px;
          line-height: 70px;
          color: #fff;
          font-weight: bold;
        }

        .myOrderOver image {
          width: 20px;
          height: 20px;
          vertical-align: middle;
        }

        .adminShowOrder {
          width: 22%;
          height: 70px;
          float: left;
          text-align: center;
          background-color: #A1D676;
          border-radius: 10px;
          margin: 5px;
          line-height: 70px;
          color: #fff;
          font-weight: bold;
        }

        .adminShowOrder:active {
          width: 22%;
          height: 70px;
          float: left;
          text-align: center;
          background-color: #94c56c;
          border-radius: 10px;
          margin: 5px;
          line-height: 70px;
          color: #fff;
          font-weight: bold;
        }

        .adminShowOrder image {
          width: 20px;
          height: 20px;
          vertical-align: middle;
        }
        .maintenanceReport {
          width: 22%;
          height: 70px;
          float: left;
          text-align: center;
          background-color: #8a8a8a;
          border-radius: 10px;
          margin: 5px;
          line-height: 70px;
          color: #fff;
          font-weight: bold;
        }
        
        .maintenanceReport:active {
          width: 22%;
          height: 70px;
          float: left;
          text-align: center;
          background-color: #8a8a8a;
          border-radius: 10px;
          margin: 5px;
          line-height: 70px;
          color: #fff;
          font-weight: bold;
        }
        
        .maintenanceReport image {
          width: 20px;
          height: 20px;
          vertical-align: middle;
        }
      }
    }

    /*分享代码*/
    .fenxiang {
      width: 80rpx;
      position: fixed;
      right: 10rpx;
      bottom: 20px;
    }

    .fenxiang image {
      width: 30px;
      height: 30px;
      max-width: 200%;
      margin: 15rpx -20rpx;
    }

    .fenxiang>button[id="ContactusBtn"] {
      background: #0d91dd;
      color: #fff;
      height: 80rpx;
      border-radius: 50%;
      margin-top: 5px;
    }

    .header-tab {
      padding: 10rpx 0;
      background-color: white;
    }
    .btn_item {
      display: flex;
      margin: 20rpx 0;
    }
  }
</style>